package top.leyi.filter;

import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import top.leyi.constant.SecurityConsts;
import top.leyi.entity.token.JwtToken;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JwtFilter extends BasicHttpAuthenticationFilter {



    /**
     * 检测Header里Authorization字段
     * 判断是否登录
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader(SecurityConsts.REQUEST_AUTH_HEADER);

        return authorization != null;
    }



    /**
     * 登录验证
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
        protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest request1 = (HttpServletRequest) request;


        String token = request1.getHeader(SecurityConsts.REQUEST_AUTH_HEADER);

        JwtToken jwtToken = new JwtToken(token);
        getSubject(request, response).login(jwtToken);
        return true;
    }

    /**
     * 是否允许访问
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        if(((HttpServletRequest) request).getRequestURI().startsWith("/user/token")){
           return true;
        }

        if (isLoginAttempt(request, response)) {
            try {
                this.executeLogin(request, response);
                String[] roleArray = (String[])mappedValue;
                if(roleArray == null || roleArray.length == 0){
                    return true;
                }
                for(String role : roleArray){
                    System.out.println(role);
                    if(getSubject(request, response).hasRole(role)){
                        return true;
                    }
                }
                throw new Exception("");
            } catch (Exception e) {
                response401(request, response, "error");
                return false;
            }
        }
        return false;
    }


    /**
     * 401非法请求
     * @param req
     * @param resp
     */
    private void response401(ServletRequest req, ServletResponse resp, String msg) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = httpServletResponse.getWriter();
            out.append("{code:400,msg:{\"token错误或已过期\"}}");
        } catch (IOException e) {
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}